import React, { useEffect, useState } from "react";

import { Upload, Modal, message, Button } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { reqListStaticImg } from "@/api/index";
import axios from "axios";

//?引入localstorage模块
import storageUtils from "@/utils/storageUtils";

function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = (error) => reject(error);
	});
}

export default function UploadImg({ type, grade, num }) {
	const [imageData, setImageData] = useState({
		imgId: null,
		previewVisible: false,
		previewImage: "",
		previewTitle: "",
		fileList: [],
		thefile: null,
		status: 0,
	});

	//? 初始化图片数据
	function initPic() {
		let fileList = [];
		reqListStaticImg().then((res) => {
			const { list } = res.data;
			let lunboArr = [];
			for (let i = 0; i < list.length; i++) {
				// 处理没有url的图片数据
				if (list[i].url === "-1") {
					delete list[i].url;
				}
				list[i].url = list[i].url;
				if (list[i].imgType == type && type == 1) {
					lunboArr.push(list[i]);
				} else if (list[i].imgType == type) {
					fileList.push(list[i]);
					setImageData((pre) => ({ ...pre, imgId: list[i].imgId }));
				}
			}
			if (type == 1) {
				let num = Number(grade);
				fileList.push(lunboArr[num]);
				setImageData((pre) => ({
					...pre,
					fileList,
					imgId: lunboArr[num].imgId,
				}));
			} else {
				setImageData((pre) => ({ ...pre, fileList }));
			}
		});
	}

	useEffect(() => {
		initPic();
	}, []);

	const beforeUpload = (file, fileList) => {
		//console.log("上传前")
		//console.log(file)
		setImageData((pre) => ({ ...pre, thefile: file, status: 1, fileList }));
	};

	const handleCancel = () =>
		setImageData((pre) => ({ ...pre, previewVisible: false }));

	const handlePreview = async (file) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj);
		}
		setImageData((pre) => ({
			...pre,
			previewImage: file.url || file.preview,
			previewVisible: true,
			previewTitle:
				file.name || file.url.substring(file.url.lastIndexOf("/") + 1),
		}));
	};

	const handleChange = ({ file, fileList }) => {
		//console.log(fileList)
		// const {imgId} = file
		// setImageData((pre) => ({ ...pre, imgId }));
		setImageData((pre) => ({ ...pre, fileList }));
		if (file.status === "done") {
			message.success("修改图片成功！");
			setImageData((pre) => ({ ...pre, status: 0 }));
		}
	};

	//?确定修改
	const change = () => {
		let formData = new FormData();
		formData.append("img", imageData.thefile);
		formData.append("imgId", imageData.imgId);
		formData.append("adminId", storageUtils.getUser().adminId);
		formData.append("type", type);
		axios({
			method: "post",
			url: "/admin/updateStaticImg",
			headers: { "Content-type": "multipart/form-data;charset=UTF-8" },
			data: formData,
		}).then((res) => {
			//console.log(res)
			if (res.data.code === 1) {
				message.success("修改成功");
				initPic();
			}
		});
	};

	const { previewVisible, previewImage, fileList, previewTitle } = imageData;

	const uploadButton = (
		<div>
			<PlusOutlined />
			<div style={{ marginTop: 8 }}>Upload</div>
		</div>
	);

	return (
		<div>
			<Upload
				// action="https://xscqa.cqupt.edu.cn/question/admin/updateStaticImg"
				action="123"
				name="img"
				// data={paramData}
				beforeUpload={beforeUpload}
				listType="picture-card"
				fileList={fileList}
				onPreview={handlePreview}
				onChange={handleChange}
				key={Math.floor(Math.random() * 10000)}
				// maxCount={3}
			>
				{fileList.length >= num ? "" : uploadButton}
			</Upload>
			<Button
				type="primary"
				disabled={imageData.status === 0}
				onClick={change}
				style={{ marginLeft: 5 }}
			>
				确定修改
			</Button>
			<Modal
				open={previewVisible}
				title={previewTitle === "-1" ? "未上传图片" : previewTitle}
				footer={null}
				onCancel={handleCancel}
			>
				{previewImage !== "-1" && (
					<img alt="example" style={{ width: "100%" }} src={previewImage} />
				)}
			</Modal>
		</div>
	);
}
